#include "app_msg.h"
Com_State app_msg_msgToJson(msg_t *msg, char *json)
{
    if(msg == NULL || json == NULL)
    {
        log_error("msg or json is null");
        return COM_ERROR;
    }
    cJSON *root = cJSON_CreateObject();
    cJSON_AddStringToObject(root, "action", msg->action);
    cJSON_AddStringToObject(root, "connetType", msg->connetType);
    cJSON_AddNumberToObject(root, "motorId", msg->motorId);
    cJSON_AddNumberToObject(root, "motorSpeed", msg->motorSpeed);
    if (msg->status != NULL)
    {
        cJSON_AddStringToObject(root, "status", msg->status);
    }
    char *str = cJSON_PrintUnformatted(root); // 会给末尾携带一个\0
    strcpy(json, str);
    free(str);
    cJSON_Delete(root);
    return COM_OK;
}

Com_State app_msg_jsonToMsg(char *json, msg_t *msg)
{
      if(msg == NULL || json == NULL)
    {
        log_error("msg or json is null");
        return COM_ERROR;
    }
    cJSON *root = cJSON_Parse(json);
    if(root == NULL)
    {
        log_error("json parse error");
        return COM_ERROR;
    }
   msg->connetType = strdup(cJSON_GetObjectItem(root, "connetType")->valuestring);
    msg->action = strdup(cJSON_GetObjectItem(root, "action")->valuestring);
    msg->motorId = cJSON_GetObjectItem(root, "motorId")->valueint;

    cJSON *motorSpeedItem = cJSON_GetObjectItem(root, "motorSpeed");
    if (motorSpeedItem != NULL)
    {
        msg->motorSpeed = motorSpeedItem->valueint;
    }

    cJSON *statusItem = cJSON_GetObjectItem(root, "status");
    if (statusItem != NULL)
    {
        msg->status = strdup(statusItem->valuestring);
    }
    cJSON_Delete(root);
}